<template>
  <div class="page-contrion">
    <div class="page-body">
      <div class="left-select-box">
        <div class="padding-content">
          <div class="box-title">{{menu_info.name}}服务列表</div>
          <el-select
          v-model="search"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading">
            <el-option v-for="item in options" :key="item.id" :label="item.appName" :value="item.addId"></el-option>
          </el-select>
          <!-- <el-input type="type" v-model="search"
            placeholder="按回车搜索"
            @keyup.enter.native="searchApps"
            suffix-icon="el-icon-search">
          </el-input> -->
        </div>
        <ul class="service-list-ul">
          <li class="service-item" :class="app_id===item.appId?'is_acitve_li': ''" v-for="(item,index) in menu_info.apps" 
              :key="index"  @click="selectApps(item.appId)">
            <span>{{item.appName}}</span>
          </li>
        </ul>
        
      </div>
      <el-form :model="prd_from" ref="prd_from" label-width="100px" label-position="top" class="demo-dynamic">
      <div class="center-select-box">
        <div class="padding-content">
          
          <div class="box-title">条件选择</div>
          <div class="params-box">
            <template v-for="(item,key) in prd_from.params">
                <el-form-item :key="key" :label="item.paramShowname"
                  :prop="'params.' + key + '.value'"
                  :rules="item.required === 1?[{ required: true, message: '请输入', trigger: !item.forSelect?'blur':'change' }]:[]">
                  <el-input  v-model="item.value" :placeholder="`请输入${item.paramShowname}`"
                    v-if="item.forSelect === '' || item.forSelect === null">
                  </el-input>
                  <el-select style="width:100%" v-model="item.value" :placeholder="`请选择${item.paramShowname}`"
                    v-if="item.forSelect !== '' && item.forSelect !== null">
                    <el-option v-for="(val,keys) in item.forSelect.split(',')" :value="val" :label="val" :key="keys"></el-option>
                  </el-select>
                </el-form-item>
            </template>
            <!-- <template v-for="(item,key) in params">
              <div class="parameter-item" :key="key">
                <div class="parameter-label">
                  <span v-if="item.required" style="color:red">*</span> {{item.paramShowname}} 
                  <el-tooltip class="item" effect="light" :content="item.paramDescription" placement="top-start">
                    <i class="icon-question"></i>
                  </el-tooltip>
                </div>
                <el-input class="select-item" v-if="!item.forSelect" v-model="item.value" placeholder="请输入"></el-input>
                <el-select v-if="item.forSelect" v-model="item.value" filterable placeholder="请选择或者输入" class="select-item">
                  <el-option
                    v-for="item in item.forSelect.split(',')"
                    :key="item"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </div>
            </template> -->
          </div>
        </div>
        <div class="center-button">
            <el-button :disabled="isVisitor || !apps_info.id" type="primary" @click="sendApi('prd_from')">发起调用</el-button>
          </div>
      </div>
      </el-form>
      <div class="right-select-box">
        <div class="padding-content">
          
          <el-link style="float:left;padding-bottom: 10px;" type="primary" icon="el-icon-download" href="/doc/获取token.docx">获取Token</el-link>
          <div class="btn-right-select">
            <div class="box-title" style="padding-bottom:0px;float:left;">API服务实际URL</div>
            <el-button type="primary" icon="el-icon-document-copy" size="small"
              :disabled="isVisitor || !apps_info.id"
              @click="copy(url)" style="float:right">复制</el-button>
          </div>
          <el-input type="textarea" :disabled="true" :value="url"
            :autosize="{ minRows: 6}" class="textarea-top"></el-input>
          <div  style="float:right;">
            <el-button type="primary" icon="el-icon-document-copy" size="small"
              :disabled="isVisitor || !apps_info.id || !debug.request || !debug.ok"
              @click="copy(debug.data)">复制</el-button>
          </div>
          <div class="box-title" style="padding-bottom:0px;">API返回结果</div>
          <el-input type="textarea"
            :value="debug.request && debug.ok ? debug.data: ''" 
            :disabled="false" :autosize="{ minRows: 6}"
            class="textar-oc textarea-top"></el-input>
        </div>
        <div class="reponst-box" v-if="debug.request">
          <div class="title" :class="debug.ok? 'success' : 'error'">{{debug.ok?'调试通过': '调试错误'}}</div>
          <div class="error-msg" v-if="!debug.ok">
            <div>{{debug.data}}</div>
          </div>
        </div>
      </div>
    </div>
    
  </div>
</template>
<script>
import { getTreeMenuInfo } from '@/api/web'
import { debugService } from '@/api/admin/debug'
import { getServiceInfo } from '@/api/admin/service'
import { getLoginType } from '@/utils/auth'
export default {
  data() {
    return {
      search: '',
      menu_info: {
        apps: []
      },
      apps: [],
      apps_info: {
        base: {
          serviceUrl: '',
          baseUrl: '',
        },
        params:[],
      },
      app_id: '',
      params: [],
      debug: {
        request: false,
      },
      url: '',
      loading: false,
      options: [],
      prd_from: {
        prd_from:[]
      },
    }
  },
  computed: {
    isVisitor() {
      return getLoginType() === 'visitor' ? true : false
    }
  },
  mounted() {
    if (this.$route.query.id){
      this.getServiceInfo(this.$route.query.id)
    }
  },
  methods: {
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.menu_info.apps.filter(item => {
            return item.appName.toLowerCase().indexOf(query.toLowerCase()) > -1
          })
        })
      }else {
        this.options = [];
      }
    },
    copy(text) {
      const vm = this;
      this.$copyText(text).then((res)=>{
        console.log(res)
        vm.$message.success('复制成功')
      },(err)=>{
        console.log(err)
        vm.$message.error('复制失败')
      })
    },
    // 调用测试接口
    sendApi(rules) {
      const vm = this;
      vm.$refs[rules].validate((valid)=>{
        if (valid) {
          let params = {
            appId:this.app_id,
          }
          let isvalid = true
          for (const item of vm.prd_from.params) {
            if (item.value !== '') {
              params[item.paramName] = item.value
            }
          }
          if (!isvalid) {
            return
          } 
          debugService(params).then((res)=>{
            vm.debug.request = true
            if (res.code === '20000') {
              vm.debug.ok = true
              vm.debug.data = res.data
            }
            if (res.code === '30006') {
              vm.debug.ok = false
              vm.debug.data = `服务未开启`
            }
            if (res.code === '30007') {
              vm.debug.ok = false
              vm.debug.data = `游客无权限调用`
            }
            if (res.code === '30008') {
              vm.debug.ok = false
              vm.debug.data = `用户无此服务调用权限`
            }
          })
        }
      })
      
      
      
    },
    async selectApps(id) {
      const vm = this;
      vm.app_id = id
      vm.apps_info.id = false
      vm.debug.request = false
      let response = await getServiceInfo({id:id})
      if (response.code === '20000') {
        vm.apps_info = response.data
        let userid_str = '${userid}';
        let token = '${token}'
        vm.url = `url: ${vm.apps_info.base.baseUrl}${vm.apps_info.base.serviceUrl}
Request Method: POST        
Request Header：
userid : ${userid_str}
token : ${token}
Content-Type : application/x-www-form-urlencoded
        `
        let temp = []
        for (const item of response.data.params) {
          let value = {
            appId: item.appId,
            forSelect: item.forSelect,
            paramShowname: item.paramShowname,
            paramName: item.paramName,
            paramDescription: item.paramDescription,
            id: item.paramDescription,
            required: item.required,
            value: ''
          }
          temp.push(value)
        }
        vm.params = temp;
        vm.prd_from.params = temp
      }
    },
    async getServiceInfo(id) {
      const vm = this;
      let id_str = String(id.replace('/',''))
      let response = await getTreeMenuInfo({id:id_str})
      if (response.code === '20000') {
        vm.menu_info = response.data
        vm.apps = response.data.apps
      }
    },
    async searchApps() {
      const vm = this;
      let temp = []
      for (const item of this.apps) {
       
        if(item.appName.indexOf(vm.search) !== -1) {
          temp.push(item)
        }
      }
      vm.menu_info.apps = temp
    }
  },
  watch:{
    $route: {
      handler: function(val){
        Object.assign(this.$data, this.$options.data())
        this.getServiceInfo(val.query.id)
      },
      // 深度观察监听
      deep: true
    }
    // console.log(this.$route)
  },
}
</script>
<style scoped>
.reponst-box {
  width: 100%;
  margin-top: 20px;
  overflow: hidden;
}
.reponst-box .title {
  padding-left: 15px;
  padding-bottom: 10px;
  font-size: 14px;
}
.success {
  color: green;
}
.error {
  color: red;
}
.error-msg {
  border: 1px solid #dedede;
  border-radius: 4px;
  margin:15px;
  height: 120px;
  overflow-x: scroll; /*x轴禁止滚动*/
  overflow-y: scroll;/*y轴滚动*/
}
.error-msg::-webkit-scrollbar {
  display: none;/*隐藏滚动条*/
}
.error-msg div{
  padding: 10px;
}
.page-body {
  position: relative;
  width: 100%;
  height: auto;
  min-height: 680px;
  _height: 680px;
  height:auto !important;
  height: 680px;
  overflow: hidden;
}
.left-select-box {
  float: left;
  width: 25%;
  background: #f5f5f5;
  position: absolute;
  bottom: 0;
  top: 0;
}
.padding-content {
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
}
.box-title {
  font-size: 14px;
  color: #666666;
  padding-top: 10px;
  padding-bottom: 20px;
}
.service-list-ul {
  margin-top: 30px;
  list-style: none;
  padding: 0;
}
.service-list-ul .service-item {
  margin: 0;
  padding: 0;
  line-height: 40px;
  padding: 0 20px;
  color: #666666;
  font-size: 14px;
}
.service-list-ul .service-item span {
  cursor: pointer;
}
.center-select-box {
  float: left;
  width: 25%;
  height: 100%;
  background: #fafafa;
  position: absolute;
  left: 25%;
  top: 0;
  bottom: 0;
}
.parameter-item {
  width: 100%;
  overflow: hidden;
  padding-bottom: 20px;
}
.parameter-label {
  font-size: 14px;
  position: relative;
  color: #666666;
}
.icon-question {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-image: url(/imgs/prompt_icon_normal.png);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position-y: 0px;
  background-position-x: 0px;
  margin-left: 2px;
  vertical-align:top;
}
.icon-question:hover {
  background-image: url(/imgs/prompt_selected.png);
}
.select-item {
  margin-top: 10px;
  width: 100%;
}
.center-button {
  position: absolute;
  bottom: 20px;
  left: 10px;
  right: 20px;
  text-align: right;
  margin-top: 10px;
}
.right-select-box {
  float: right;
  width: 50%;
  height: 100%;
  background: #ffffff;
  position: absolute;
  left: 50%;
  border-left: 1px solid #f8f8f8;
}
.btn-right-select {
  width: 100%;
  overflow: hidden;
}
.textarea-top {
  margin-top: 20px;
  margin-bottom: 20px;
}
.is_acitve_li {
  background: #94ebff60;
}
.parameter-label span {
  color:#1598eb;
}
.desption {
  position: absolute;
  top: -30px;
  z-index: 999;
  display: none;
  color:#1598eb;
}
.params-box {
  width: 100%;
  height: 550px;
  overflow: scroll;
}
.params-box::-webkit-scrollbar {
  display: none;
}
</style>